package com.glsc.ngateway.flowable.listener.global;

import cn.hutool.core.collection.CollectionUtil;
import com.glsc.ngateway.common.api.flowable.dto.Result;
import com.glsc.ngateway.common.api.flowable.dto.demand.FlowableAssigneeDto;
import com.glsc.ngateway.flowable.constant.FlowableConstant;
import com.glsc.ngateway.flowable.service.FlowableAssigneeService;
import com.glsc.ngateway.flowable.service.FlowableUserService;
import com.glsc.ngateway.flowable.service.feignservice.AmproductFeignService;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEntityEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEntityEvent;
import org.flowable.engine.FormService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.delegate.event.AbstractFlowableEngineEventListener;
import org.flowable.engine.impl.persistence.entity.ExecutionEntity;
import org.flowable.engine.runtime.ProcessInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class ProcessStartListener extends AbstractFlowableEngineEventListener {

    private static Logger logger = LoggerFactory.getLogger(ProcessStartListener.class);

//    public static ProcessStartListener processStartListener;

    @Autowired
    private FlowableUserService flowableUserService;
    @Autowired
    private FlowableAssigneeService flowableAssigneeService;

    @Autowired
    private AmproductFeignService amproductFeignService;

    @Autowired
    private TaskService taskService;
    @Autowired
    private FormService formService;
    @Autowired
    private RuntimeService runtimeService;


    @Override
    public void processCreated(FlowableEngineEntityEvent event) {

        try {

            logger.info("进入processCreated监听器……");
            FlowableEntityEvent ee = (FlowableEntityEvent) event;
            ProcessInstance p = (ProcessInstance) ee.getEntity();
            Map<String, Object> variableMap = new HashMap<>();
            ExecutionEntity en = (ExecutionEntity) ee.getEntity();

            String sysid = p.getTenantId();
            List<FlowableAssigneeDto> list = flowableAssigneeService.findAssigneeByKey(event.getProcessDefinitionId().split(":")[0], sysid);
            if (CollectionUtil.isEmpty(list)) {
                return;
            }

            for (FlowableAssigneeDto fa : list) {
                if ("0".equals(fa.getType())) {
                    //0直接用数据库的人员，逗号分隔
                    String[] assignee = fa.getAssigneeName().split(",");
                    if (assignee.length == 1 && !fa.getAssigneeVariable().contains("Group")) {
                        en.setVariable(fa.getAssigneeVariable(), assignee[0]);
                        logger.info("创建流程初始化办理人" + fa.getAssigneeVariable() + ":" + assignee[0]);
                    } else {
                        List<String> aslist = new ArrayList<>();
                        for (String s : assignee) {
                            aslist.add(s);
                        }
                        variableMap.put(fa.getAssigneeVariable(), aslist);
                        variableMap.put(fa.getAssigneeVariable() + "Size", assignee.length);

                        en.setVariable(fa.getAssigneeVariable(), aslist);
                        en.setVariable(fa.getAssigneeVariable() + "Size", assignee.length);

                        logger.info("创建流程初始化办理人" + fa.getAssigneeVariable() + ":" + fa.getAssigneeName());
                    }
                } else {
                    //1取数据库配置
                    String[] syslist = fa.getSysid().split("\\|");
                    String[] rolelist = fa.getRoleName().split("\\|");
                    int index = Arrays.binarySearch(syslist, sysid);
                    String role = rolelist[index];
                    if (sysid.equals(FlowableConstant.AMPROD)) {
                        Result<List<String>> group = amproductFeignService.findAmProductUserIdList(role);
                        if (group.getCode() == 10000) {
                            variableMap.put(fa.getAssigneeVariable(), group.getData());
                            variableMap.put(fa.getAssigneeVariable() + "Size", group.getData().size());

                            en.setVariable(fa.getAssigneeVariable(), group.getData());
                            en.setVariable(fa.getAssigneeVariable() + "Size", group.getData().size());

                            logger.info("创建流程初始化办理人" + fa.getAssigneeVariable() + ":" + group.getData());
                        } else {
                            logger.error("进入processCreated监听器异常！" + group.toString());
                        }
                    }

                }
            }
            // runtimeService.setVariables(event.getExecutionId(), variableMap);
            // Map<String, Object> variables = runtimeService.getVariables(event.getProcessInstanceId());
            // super.processCreated(event);

        } catch (Exception e) {
            logger.error("进入processCreated监听器异常！", e);
        }

    }
}